import { postAnswer } from "@/services/answer";
import type { NextApiRequest, NextApiResponse } from "next";

const getAnswerInfo = (reqBody:any) =>{
  const answerList:any[] = []

  Object.keys(reqBody).forEach(key=>{
    if(key === 'questionId') return 
    answerList.push({
      componentId:key,
      value:reqBody[key]
    })
  })

  return {
    questionId:reqBody.questionId || '',
    answerList
  }
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    const {method,body} = req
    if(method !== 'POST' )  return res.status(200).json({errno:-1,errmsg:'请求方式错误'})

    const answerInfo = getAnswerInfo(body)
    console.log('answerInfo:',answerInfo)
    try{
      // 提交到服务端
      const resData = await postAnswer(answerInfo) as any

      console.log('data:',resData)

      if(resData.errno == 0){
        // 如果提交成功了
        res.redirect('/success')
      }else{
        res.redirect('/fail')
      }
    }catch{
       res.redirect('/fail')
    }

    return res.status(200).json({errno:0,errmsg:'success'})
}